<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Upload, Eleme, OfficeBuilding } from '@element-plus/icons-vue'
import { userAPI } from '@/apis/user.js'

// 定义emit事件
const emit = defineEmits(['openLogin', 'openRegister'])

// 控制对话框显示
const dialogVisible = ref(false)

// 表单数据
const externalRegisterForm = reactive({
  nickname: '',
  email: '',
  password: '',
  confirmPassword: '',
  support: null,
  verificationCode: '',
  institution: ''
})

// 表单引用
const externalRegisterFormRef = ref()
const loading = ref(false)

// 文件上传相关
const fileInputRef = ref()
const supportImagePreview = ref('')
const uploadingSupportImage = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)
let countdownTimer = null

// 确认密码验证
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('Please confirm your password'))
  } else if (value !== externalRegisterForm.password) {
    callback(new Error('The two passwords do not match'))
  } else {
    callback()
  }
}

// 表单验证规则
const rules = {
  nickname: [
    { required: true, message: 'Please input username', trigger: 'blur' },
    { min: 3, max: 20, message: 'The username length ranges from 3 to 20 characters', trigger: 'blur' }
  ],
  email: [
    { required: true, message: 'Please input email', trigger: 'blur' },
    { type: 'email', message: 'Please input a valid email address', trigger: 'blur' }
  ],
  password: [
    { required: true, message: 'Please input the password', trigger: 'blur' },
    { min: 6, max: 20, message: 'Password length is between 6 and 20 characters', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: 'Please confirm your password', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  support: [
    { required: true, message: 'Please upload proof image', trigger: 'change' }
  ],
  institution: [
      { required: true, message: 'Please input institution', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: 'Please input verification code', trigger: 'blur' },
    { min: 6, max: 6, message: 'Verification code length is 6 digits', trigger: 'blur' }
  ]
}

// 打开对话框
const openExternalRegisterDialog = () => {
  dialogVisible.value = true
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  
  // 重置表单
  if (externalRegisterFormRef.value) {
    externalRegisterFormRef.value.resetFields()
  }
  externalRegisterForm.nickname = ''
  externalRegisterForm.email = ''
  externalRegisterForm.password = ''
  externalRegisterForm.confirmPassword = ''
  externalRegisterForm.support = null
  externalRegisterForm.verificationCode = ''
  externalRegisterForm.institution = ''
  supportImagePreview.value = ''
  // 停止倒计时
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
  sendingCode.value = false
  countdown.value = 0
}

// 触发文件选择
const triggerFileInput = () => {
  fileInputRef.value?.click()
}

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('Only JPG, PNG, GIF image formats are supported')
    return
  }

  // 验证文件大小
  const maxSize = 10 * 1024 * 1024
  if (file.size > maxSize) {
    ElMessage.error('Image size cannot exceed 5MB')
    return
  }

  // 设置文件和预览
  externalRegisterForm.support = file
  
  // 创建预览URL
  const reader = new FileReader()
  reader.onload = (e) => {
    supportImagePreview.value = e.target.result
  }
  reader.readAsDataURL(file)
}

// 上传证明图片
const uploadSupportImage = async () => {
  if (!externalRegisterForm.support) return null

  try {
    uploadingSupportImage.value = true
    const formData = new FormData()
    formData.append('image', externalRegisterForm.support)
    
    const response = await userAPI.uploadSupportImage(formData)
    
    if (response && response.status === 'success') {
      return response.data.imageUrl
    }
    throw new Error('Upload failed')
  } catch (error) {
    ElMessage.error('Failed to upload proof image')
    throw error
  } finally {
    uploadingSupportImage.value = false
  }
}

// 外部用户注册提交
const handleExternalRegister = async () => {
  if (!externalRegisterFormRef.value) return

  try {
    const valid = await externalRegisterFormRef.value.validate()
    if (valid) {
      loading.value = true

      // 先上传证明图片
      const supportImageUrl = await uploadSupportImage()

      // 调用外部用户注册API
      const response = await userAPI.externalRegister({
        email: externalRegisterForm.email,
        nickname: externalRegisterForm.nickname,
        password: externalRegisterForm.password,
        support: supportImageUrl,
        verificationCode: externalRegisterForm.verificationCode,
        institution: externalRegisterForm.institution
      })

      // 注册成功
      if (response && response.status === 'success') {
        ElMessage.success('External user registration submitted successfully! Please wait for approval.')
        closeDialog()
        // 触发父组件打开登录对话框
        emit('openLogin')
      }
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

// 跳转到普通注册页面
const goToRegister = () => {
  closeDialog()
  // 触发父组件打开普通注册对话框
  emit('openRegister')
}

// 暴露方法给父组件调用
defineExpose({
  openExternalRegisterDialog
})

const handleSendCode = async () => {
  if (!externalRegisterForm.email) {
    ElMessage.error('Please input email first')
    return
  }
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(externalRegisterForm.email)) {
    ElMessage.error('Please input a valid email address')
    return
  }
  try {
    sendingCode.value = true
    const response = await userAPI.sendExternalVerificationCode({ email: externalRegisterForm.email })
    if (response && response.status === 'success') {
      ElMessage.success('Verification code sent successfully')
      countdown.value = 60
      countdownTimer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(countdownTimer)
          countdownTimer = null
        }
      }, 1000)
    }
  } catch (error) {
    console.log(error)
  } finally {
    sendingCode.value = false
  }
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    width="420px"
    :before-close="closeDialog"
    :show-close="false"
    class="external-register-dialog"
    center
  >
    <template #header>
      <div class="external-register-header">
        <span>External User Registration</span>
      </div>
    </template>
    <el-form
      ref="externalRegisterFormRef"
      :model="externalRegisterForm"
      :rules="rules"
      class="external-register-form"
    >
      <el-form-item prop="nickname">
        <el-input
          v-model="externalRegisterForm.nickname"
          placeholder="Please input username"
          :maxlength="150"
          clearable
          size="large"
          :prefix-icon="User"
        />
      </el-form-item>

      <el-form-item prop="institution">
        <el-input
            v-model="externalRegisterForm.institution"
            placeholder="Please input institution"
            :maxlength="150"
            clearable
            size="large"
            :prefix-icon="OfficeBuilding"
        />
      </el-form-item>
      
      <el-form-item prop="email">
        <el-input
          v-model="externalRegisterForm.email"
          placeholder="Please input email address"
          :maxlength="150"
          clearable
          size="large"
          :prefix-icon="Message"
        />
      </el-form-item>
      
      <el-form-item prop="verificationCode">
        <div class="verification-code-container">
          <el-input
            v-model="externalRegisterForm.verificationCode"
            placeholder="Please input verification code"
            :maxlength="6"
            clearable
            size="large"
            class="verification-input"
            :prefix-icon="Eleme"
          />
          <el-button
            class="send-code-btn"
            :loading="sendingCode"
            :disabled="countdown > 0"
            @click="handleSendCode"
            size="large"
          >{{ countdown > 0 ? `${countdown}s` : 'Send Code' }}</el-button>
        </div>
      </el-form-item>
      
      <el-form-item prop="password">
        <el-input
          v-model="externalRegisterForm.password"
          type="password"
          placeholder="Please input password"
          show-password
          :maxlength="150"
          clearable
          size="large"
          :prefix-icon="Lock"
        />
      </el-form-item>
      
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="externalRegisterForm.confirmPassword"
          type="password"
          placeholder="Please confirm password"
          show-password
          :maxlength="150"
          clearable
          size="large"
          :prefix-icon="Lock"
        />
      </el-form-item>
      
      <el-form-item prop="support">
        <div class="support-upload-container">
          <div class="upload-area" @click="triggerFileInput">
            <div v-if="!supportImagePreview" class="upload-placeholder">
              <el-icon size="40" color="#c0c4cc">
                <Upload />
              </el-icon>
              <div class="upload-text">
                <div>Click to upload proof image</div>
                <div class="upload-tip">Support JPG, PNG, GIF formats, max 5MB</div>
              </div>
            </div>
            <div v-else class="image-preview">
              <img :src="supportImagePreview" alt="Proof image preview" />
              <div class="image-overlay">
                <span>Click to change</span>
              </div>
            </div>
          </div>
          <input
            ref="fileInputRef"
            type="file"
            accept="image/*"
            style="display: none"
            @change="handleFileChange"
          />
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <div class="register-link">
          <span>Campus user?</span>
          <el-button type="text" @click="goToRegister">Campus User Registration</el-button>
        </div>
        <div class="button-group">
          <el-button @click="closeDialog">Cancel</el-button>
          <el-button
            type="primary"
            @click="handleExternalRegister"
            :loading="loading && uploadingSupportImage"
          >
            Submit
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.external-register-header {
  font-size: 24px;
}

.external-register-form {
  .el-form-item {
    margin-bottom: 24px;
  }
  
  .verification-code-container {
    display: flex;
    gap: 10px;
    width: 100%;

    .verification-input {
      flex: 1;
    }
    
    .send-code-btn {
      width: 100px;
    }
  }
  
  .support-upload-container {
    width: 100%;
    
    .upload-area {
      width: 100%;
      height: 120px;
      border: 2px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: border-color 0.3s;
      
      &:hover {
        border-color: #409EFF;
      }
      
      .upload-placeholder {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        
        .upload-text {
          margin-top: 8px;
          text-align: center;
          
          div:first-child {
            color: #606266;
            font-size: 14px;
          }
          
          .upload-tip {
            color: #909399;
            font-size: 12px;
            margin-top: 4px;
          }
        }
      }
      
      .image-preview {
        position: relative;
        width: 100%;
        height: 100%;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .image-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.5);
          display: flex;
          align-items: center;
          justify-content: center;
          opacity: 0;
          transition: opacity 0.3s;
          
          span {
            color: white;
            font-size: 14px;
          }
        }
        
        &:hover .image-overlay {
          opacity: 1;
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  gap: 16px;

  .register-link {
    text-align: left;
    color: #666;
    font-size: 14px;

    span {
      margin-right: 4px;
    }

    .el-button {
      padding: 0;
      font-size: 14px;
      color: #409EFF;

      &:hover {
        color: #66b1ff;
      }
    }
  }

  .button-group {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    gap: 5px;
  }
}
</style>